# ~*~ coding: utf-8 ~*~
import time

from apps.common.dbbase import BaseModel
from apps.common.utils import generate_uuid
from apps.extensions import db

from celery import schedules

__all__ = ['CrontabSchedule']


class CrontabSchedule(BaseModel):
    __tablename__ = 'tasks_periodic_schedule_crontab'

    id = db.Column(db.String(36), default=generate_uuid, primary_key=True)
    minute = db.Column(db.String(60 * 4), default='*')
    hour = db.Column(db.String(24 * 4), default='*')
    day_of_week = db.Column(db.String(64), default='*')
    day_of_month = db.Column(db.String(31 * 4), default='*')
    month_of_year = db.Column(db.String(64), default='*')

    create_by = db.Column(db.VARCHAR(32), nullable=True)
    create_time = db.Column(db.INT, default=time.time)
    update_time = db.Column(db.INT, default=time.time, onupdate=time.time)

    @property
    def schedule(self):
        return schedules.crontab(
            minute=self.minute,
            hour=self.hour,
            day_of_week=self.day_of_week,
            day_of_month=self.day_of_month,
            month_of_year=self.month_of_year,
        )

    def __str__(self):
        return ' '.join([self.minute, self.hour, self.day_of_month, self.month_of_year, self.day_of_week])

